package com.kly.module_base.utils

import java.text.DecimalFormat

/**
 * @ClassName: DecimaUtil
 * @Description:
 * @Author: You
 */
class DecimalUtil {
    companion object {
        fun toDecimal(v: Long?): String {
            if (v == null) {
                return "0"
            }
            return String.format("%.2f", v / 100f)
        }

        /**
         * 金额转化
         *
         * @param money
         * @param isAddSymbol 是否增加 ¥ 符号
         * @param customSymbol 增加 自定义 符号
         * @return
         */
        fun longToTwoDecimalPlaces(
            money: Long?,
            isAddSymbol: Boolean? = false,
            customSymbol: String? = null,
            defaultStr: String = "0"
        ): String {
            if (money == null || money == 0L) {
                if (isAddSymbol!!) {
                    return(customSymbol ?: "¥ ") + defaultStr
                }else{
                    return defaultStr
                }
            }
            var result: String
            try {
                if (money.toString().length >= 8) {
                    result = money.toString()
                    val stringBuilde = StringBuilder()
                    stringBuilde.append(result)
                    stringBuilde.insert(result.length - 2, ".")
                    result = stringBuilde.toString().replace("0+?$".toRegex(), "") //去掉后面无用的零
                    result = result.replace("[.]$".toRegex(), "") //如小数点后面全是零则去掉小数点
                    return result
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            val df = DecimalFormat("0.00")
            result = df.format((money.toFloat() / 100).toDouble())
            result = result.replace("0+?$".toRegex(), "") //去掉后面无用的零
            result = result.replace("[.]$".toRegex(), "") //如小数点后面全是零则去掉小数点

            if (isAddSymbol!!) {
                result = (customSymbol ?: "¥ ") + result
            }
            return result
        }
    }
}